const inheritProps = (vm) => {
  let props
  if (Object.prototype.toString.call(vm.$attrs) == '[object Undefined]' && Object.prototype.toString.call(vm.$props) == '[object Undefined]') {
    props = {
      ...vm
    }
  } else {
    let attrs = vm.$attrs

    Object.keys(attrs).forEach(attr => {
      switch (attr) {
        case '':
          delete attrs[attr]
          break
      }
    })

    props = {
      ...vm.$props,
      ...attrs
    }
  }

  // 全局设置表单组件的size
  if (/^bl-(form-|button)/.test(props.componentName) && !props.hasOwnProperty('size')) {
    props.size = ''
  }

  return props
}

const inheritListeners = (vm) => {
  let listeners = {}
  let attrs = vm.$attrs

  if (Object.prototype.toString.call(vm.$attrs) == '[object Undefined]' && Object.prototype.toString.call(vm.$props) == '[object Undefined]') {
    attrs = {
      ...vm
    }
  }

  Object.keys(attrs).forEach(attr => {
    if (attr.startsWith('_') && Object.prototype.toString.call(attrs[attr]) === '[object Function]') {
      let emitAttr = attr.replace(/^_(?!_)/, '').toKebabCase()

      listeners[emitAttr] = attrs[attr]

      // delete attrs[attr]
    }
  })

  let newListeners = Object.assign({},
    listeners,
    vm.$listeners
  )

  delete newListeners['async-mounted']

  return newListeners
}

function MyinheritMethods ({
  vm,
  refName,
  source,
  inherit
}) {
  let methods = {}

  source = source || vm.$refs[refName] || {}

  Object.keys(source).forEach(propertyName => {
    if (Object.prototype.toString.call(source[propertyName]) === '[object Function]' && /^(?!_|\$|handle|on).*/.test(propertyName)) {
      methods[propertyName] = source[propertyName]

      if (inherit && vm && Object.prototype.toString.call(vm[propertyName]) === '[object Undefined]') {
        vm[propertyName] = methods[propertyName]
      }
    }
  })

  return methods
}

// 继承方法
const inheritMethods = ({
  vm,
  refName,
  source,
  inherit = true
}) => {
  let methods = {}

  if (Object.prototype.toString.call(refName) == '[object String]') {
    refName = [refName]
  }

  if (Object.prototype.toString.call(refName) == '[object Array]') {
    refName.forEach(name => {
      methods[name] = {}

      Object.assign(methods[name], MyinheritMethods({
        vm,
        refName: name,
        inherit
      }))
    })
  } else {
    Object.assign(methods, MyinheritMethods({
      vm,
      source,
      inherit
    }))
  }

  return methods
}

// 继承父组件数据挂载对象
const vueInherit = {
  inheritProps,
  inheritListeners,
  inheritMethods
}

export default vueInherit
